package fr.afcepf.iziticket.dao;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.classic.Session;
import org.hibernate.criterion.Expression;
import org.hibernate.criterion.Restrictions;

import fr.afcepf.iziticket.dao.ObjectDaoImpl;
import fr.afcepf.iziticket.dao.interfaces.DAOSeance;
import fr.afcepf.iziticket.entities.Reservation;
import fr.afcepf.iziticket.entities.Seance;
import fr.afcepf.iziticket.entities.Spectacle;

public class DAOSeanceImpl extends ObjectDaoImpl<Seance> implements DAOSeance {

	@Override
	public Seance get(int paramId) {
	
		return (Seance) hibernateTemplate.get(Seance.class, paramId);
	
	}

	public DAOSeanceImpl() {
		super();
		setTableName("Seance");
	}


	public Seance getSeanceFromReservation(int idResa) {
		Reservation resa = (Reservation) hibernateTemplate.get(Reservation.class,  idResa);
		return resa.getSeance();
	}


	@SuppressWarnings("unchecked")
	public List<Seance> getSeanceBySpectacleIdAndByMonth(int idSpectacle,
			int month, int year) {
		Session session = sessionFactory.openSession();
		Criteria criteria = session.createCriteria(Seance.class);
		
		Spectacle spectacle = (Spectacle) hibernateTemplate.get(Spectacle.class, idSpectacle);
		DateFormat df = new SimpleDateFormat("dd-MM-yyyy"); 
		Date date;
		try {
			date = df.parse("01-"+month+"-"+year);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		Date startDate = cal.getTime();
		cal.add(Calendar.MONTH, 1);
		Date endDate = cal.getTime();
		
		/*StringBuilder query = new StringBuilder("from Seance");
		query.append(" where dateSeance >= :startDate and dateseance<=:endDate");
		query.append(" and idSpectacle=:idSpectacle");
		query.append( " order by dateSeance");
		
		String[] params = {"startDate", "endDate","idSpectacle"};
		Object[] values = {startDate, endDate, idSpectacle};
		return (List<Seance>) hibernateTemplate.findByNamedParam(query.toString(), params , values);*/
		criteria.add(Restrictions.between("dateSeance", startDate, endDate));
		criteria.add(Restrictions.eq("spectacle", spectacle));
		
		return (List<Seance>) criteria.list();
		
	}
	
	
	
	
	
}
